package com.ssy.lingxi.member.merchant.serviceimpl.base;

import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.member.MemberStatusEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.constant.MemberRelationTypeEnum;
import com.ssy.lingxi.member.merchant.api.constant.MemberRightReturnTypeEnum;
import com.ssy.lingxi.member.merchant.api.constant.MemberRightTypeEnum;
import com.ssy.lingxi.member.merchant.api.model.constant.MemberRightSpendTypeEnum;
import com.ssy.lingxi.member.merchant.entity.*;
import com.ssy.lingxi.member.merchant.model.constant.MemberStringEnum;
import com.ssy.lingxi.member.merchant.model.constant.MemberValidateStatusEnum;
import com.ssy.lingxi.member.merchant.repository.MemberLevelRightRepository;
import com.ssy.lingxi.member.merchant.repository.MemberRelationRepository;
import com.ssy.lingxi.member.merchant.repository.MemberRightHistoryRepository;
import com.ssy.lingxi.member.merchant.repository.MemberRightSpendHistoryRepository;
import com.ssy.lingxi.member.merchant.service.base.IBaseMemberLevelAsyncService;
import com.ssy.lingxi.member.merchant.service.base.IBaseMemberLrcCacheService;
import com.ssy.lingxi.member.merchant.service.base.IBaseMemberRightAsyncService;
import com.ssy.lingxi.member.merchant.service.feign.IPayFeignService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 会员权益相关计算异步接口实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2020-11-18
 */
@Service
public class BaseMemberRightAsyncServiceImpl implements IBaseMemberRightAsyncService {
    private static final Logger logger = LoggerFactory.getLogger(BaseMemberRightAsyncServiceImpl.class);

    @Resource
    private IBaseMemberLrcCacheService lrcCacheService;

    @Resource
    private IBaseMemberLevelAsyncService baseMemberLevelAsyncService;

    @Resource
    private MemberRelationRepository relationRepository;

    @Resource
    private MemberLevelRightRepository memberLevelRightRepository;

    @Resource
    private MemberRightHistoryRepository memberRightHistoryRepository;

    @Resource
    private MemberRightSpendHistoryRepository memberRightSpendHistoryRepository;

    @Resource
    private IPayFeignService payFeignService;

    /**
     * 交易完成后，同时计算下级会员的交易返现金额、权益积分，再计算等级积分
     *
     * @param upperMemberId 上级会员Id（卖方）
     * @param upperRoleId   上级会员角色Id
     * @param subMemberId   下级会员Id（买方）
     * @param subRoleId     下级会员角色Id
     * @param tradeAmount   交易金额
     * @param orderNo       订单号
     */
    @Async
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public void calculateMemberTradeRightThenLevelScore(Long upperMemberId, Long upperRoleId, Long subMemberId, Long subRoleId, Double tradeAmount, String orderNo) {
        //Step 1: 计算权益
        calculateMemberTradeRight(upperMemberId, upperRoleId, subMemberId, subRoleId, tradeAmount, orderNo);

        //Step 2: 再计算等级（由于升级后，关联的权益会变化，所以要先计算权益，再计算等级）
        baseMemberLevelAsyncService.calculateSubMemberTradeScore(upperMemberId, upperRoleId, subMemberId, subRoleId, tradeAmount, orderNo);
    }

    /**
     * 交易完成后，同时计算下级会员的交易返现金额、权益积分
     *
     * @param upperMemberId 上级会员Id（卖方）
     * @param upperRoleId   上级会员角色Id
     * @param subMemberId   下级会员Id（买方）
     * @param subRoleId     下级会员角色Id
     * @param tradeAmount   交易金额
     * @param orderNo       订单号
     */
    @Override
    public void calculateMemberTradeRight(Long upperMemberId, Long upperRoleId, Long subMemberId, Long subRoleId, Double tradeAmount, String orderNo) {
        try {
            //Step 1: 查询会员关系，如果存在则计算会员权益
            MemberRelationDO relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(upperMemberId, upperRoleId, subMemberId, subRoleId);
            if (relationDO != null && relationDO.getVerified().equals(MemberValidateStatusEnum.VERIFY_PASSED.getCode()) && relationDO.getStatus().equals(MemberStatusEnum.NORMAL.getCode()) && !calculateSubMemberTradeRight(relationDO, tradeAmount, orderNo)) {
                return;
            }

            //Step 2: 查询下级会员的平台关系，计算平台权益积分
            MemberRelationDO platformMemberRelationDO = relationRepository.findFirstBySubMemberIdAndSubRoleIdAndRelType(subMemberId, subRoleId, MemberRelationTypeEnum.PLATFORM.getCode());
            if(platformMemberRelationDO == null) {
                logger.error(String.format("计算会员权益错误，会员Id:%d , 角色Id: %d 没有平台会员关系", subMemberId, subRoleId));
                return;
            }

            if(platformMemberRelationDO.getVerified().equals(MemberValidateStatusEnum.VERIFY_PASSED.getCode()) && platformMemberRelationDO.getStatus().equals(MemberStatusEnum.NORMAL.getCode())) {
                calculateSubMemberTradeRight(platformMemberRelationDO, tradeAmount, orderNo);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("计算会员权益错误", e);
        }
    }

    /**
     * 交易完成后，计算下级会员的交易返现金额
     * @param upperMemberId 上级会员Id（卖方）
     * @param upperRoleId   上级会员角色Id
     * @param subMemberId   下级会员Id（买方）
     * @param subRoleId     下级会员角色Id
     * @param tradeAmount   交易金额
     * @param orderNo       订单号
     * @return 异步计算结果
     */
    @Async
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public CompletableFuture<Boolean> calculateMemberReturnMoney(Long upperMemberId, Long upperRoleId, Long subMemberId, Long subRoleId, Double tradeAmount, String orderNo) {
        try {
            //Step 1: 查询会员关系，如果存在则计算会员权益
            MemberRelationDO relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(upperMemberId, upperRoleId, subMemberId, subRoleId);
            if (relationDO != null && relationDO.getVerified().equals(MemberValidateStatusEnum.VERIFY_PASSED.getCode()) && relationDO.getStatus().equals(MemberStatusEnum.NORMAL.getCode()) && !separateCalculateSubMemberRight(relationDO, MemberRightTypeEnum.RETURN_MONEY_RIGHT, tradeAmount, orderNo)) {
                return CompletableFuture.completedFuture(false);
            }
            
            //Step 2: 查询下级会员的平台关系，计算平台等级积分
            MemberRelationDO platformMemberRelationDO = relationRepository.findFirstBySubMemberIdAndSubRoleIdAndRelType(subMemberId, subRoleId, MemberRelationTypeEnum.PLATFORM.getCode());
            if(platformMemberRelationDO == null) {
                logger.error(String.format("计算会员返现权益错误，会员Id:%d , 角色Id: %d 没有平台会员关系", subMemberId, subRoleId));
                return CompletableFuture.completedFuture(false);
            }

            if(platformMemberRelationDO.getVerified().equals(MemberValidateStatusEnum.VERIFY_PASSED.getCode()) && platformMemberRelationDO.getStatus().equals(MemberStatusEnum.NORMAL.getCode())) {
                return CompletableFuture.completedFuture(separateCalculateSubMemberRight(platformMemberRelationDO, MemberRightTypeEnum.RETURN_MONEY_RIGHT, tradeAmount, orderNo));
            }

            return CompletableFuture.completedFuture(true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("计算会员返现权益错误", e);
            return CompletableFuture.completedFuture(false);
        }
    }

    /**
     * 交易完成后，计算下级会员的权益积分
     *
     * @param upperMemberId 上级会员Id（卖方）
     * @param upperRoleId   上级会员角色Id
     * @param subMemberId   下级会员Id（买方）
     * @param subRoleId     下级会员角色Id
     * @param tradeAmount   交易金额
     * @param orderNo       订单号
     * @return 异步计算结果
     */
    @Async
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public CompletableFuture<Boolean> calculateMemberRightScore(Long upperMemberId, Long upperRoleId, Long subMemberId, Long subRoleId, Double tradeAmount, String orderNo) {
        try {
            //Step 1: 查询会员关系，如果存在则计算会员权益
            MemberRelationDO relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(upperMemberId, upperRoleId, subMemberId, subRoleId);
            if (relationDO != null && relationDO.getVerified().equals(MemberValidateStatusEnum.VERIFY_PASSED.getCode()) && relationDO.getStatus().equals(MemberStatusEnum.NORMAL.getCode()) && !separateCalculateSubMemberRight(relationDO, MemberRightTypeEnum.SCORE_POINTS_RIGHT, tradeAmount, orderNo)) {
                return CompletableFuture.completedFuture(false);
            }

            //Step 2: 查询下级会员的平台关系，计算平台等级积分
            MemberRelationDO platformMemberRelationDO = relationRepository.findFirstBySubMemberIdAndSubRoleIdAndRelType(subMemberId, subRoleId, MemberRelationTypeEnum.PLATFORM.getCode());
            if(platformMemberRelationDO == null) {
                logger.error(String.format("计算会员积分权益错误，会员Id:%d , 角色Id: %d 没有平台会员关系", subMemberId, subRoleId));
                return CompletableFuture.completedFuture(false);
            }

            if(platformMemberRelationDO.getVerified().equals(MemberValidateStatusEnum.VERIFY_PASSED.getCode()) && platformMemberRelationDO.getStatus().equals(MemberStatusEnum.NORMAL.getCode())) {
                return CompletableFuture.completedFuture(separateCalculateSubMemberRight(platformMemberRelationDO, MemberRightTypeEnum.SCORE_POINTS_RIGHT, tradeAmount, orderNo));
            }

            return CompletableFuture.completedFuture(true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("计算会员积分权益错误", e);
            return CompletableFuture.completedFuture(false);
        }
    }

    /**
     * 积分支付完成后，计算下级会员的权益消费积分
     *
     * @param relationDO  会员关系
     * @param spentAmount 消费的积分
     * @param spentType   消费的项目枚举
     * @param orderNo     订单号
     */
    @Async
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public void calculateMemberRightSpendScore(MemberRelationDO relationDO, Integer spentAmount, Integer spentType, String orderNo) {
        try {
            MemberLevelRightDO levelRightDO = relationDO.getLevelRight();
            if(levelRightDO == null) {
                return;
            }

            levelRightDO.setSumUsedPoint(levelRightDO.getSumUsedPoint() + spentAmount);
            levelRightDO.setCurrentPoint(levelRightDO.getSumPoint() - levelRightDO.getSumUsedPoint());
            memberLevelRightRepository.saveAndFlush(levelRightDO);

            //权益消费记录
            MemberRightSpendHistoryDO historyDO = new MemberRightSpendHistoryDO();
            historyDO.setCreateTime(LocalDateTime.now());
            historyDO.setRelType(relationDO.getRelType());
            historyDO.setMemberId(relationDO.getMemberId());
            historyDO.setRoleId(relationDO.getRoleId());
            historyDO.setSubMemberId(relationDO.getSubMemberId());
            historyDO.setSubRoleId(relationDO.getSubRoleId());
            historyDO.setRightTypeEnum(MemberRightTypeEnum.SCORE_POINTS_RIGHT.getCode());
            historyDO.setRightTypeName(MemberRightTypeEnum.SCORE_POINTS_RIGHT.getMessage());
            historyDO.setSpendTypeEnum(spentType);
            historyDO.setSpendTypeName(MemberRightSpendTypeEnum.parse(spentType).getTypeName());
            historyDO.setPoint(spentAmount);
            historyDO.setRemark(MemberRightSpendTypeEnum.isOrder(spentType) ? MemberStringEnum.ORDER_NO.getName().concat(":").concat(orderNo) : MemberStringEnum.COUPON_NO.getName().concat(":").concat(orderNo));
            historyDO.setBusinessNo(orderNo);
            memberRightSpendHistoryRepository.saveAndFlush(historyDO);

            //缓存
            if(relationDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())) {
                lrcCacheService.cacheMemberRight(relationDO.getSubMemberId(), relationDO.getSubRoleId(), levelRightDO.getSumReturnMoney().doubleValue(), levelRightDO.getSumPoint(), levelRightDO.getCurrentPoint(), levelRightDO.getSumUsedPoint());
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("计算下级会员的权益消费积分错误", e);
        }
    }


    /**
     * 单独计算每项权益积分
     * @param relationDO 会员关系
     * @param memberRightTypeEnum 权益类型枚举
     * @param tradeAmount 交易金额
     * @param orderNo 订单号
     * @return 是否成功
     */
    private Boolean separateCalculateSubMemberRight(MemberRelationDO relationDO, MemberRightTypeEnum memberRightTypeEnum, Double tradeAmount, String orderNo) {
        //查询权益，如果没有，返回
        //下级会员的当前等级信息
        MemberLevelRightDO levelRightDO = relationDO.getLevelRight();
        if (levelRightDO == null) {
            logger.error("计算" + memberRightTypeEnum.getMessage()  + "： 会员RelationId:" + relationDO.getId() + "没有当前等级数据");
            return false;
        }

        MemberLevelConfigDO memberLevelConfigDO = levelRightDO.getLevelConfig();
        if(memberLevelConfigDO == null || CollectionUtils.isEmpty(memberLevelConfigDO.getRights())) {
            return true;
        }

        MemberRightConfigDO memberRightConfigDO = memberLevelConfigDO.getRights().stream().filter(right -> right.getRightType().equals(memberRightTypeEnum.getCode())).findFirst().orElse(null);
        if(memberRightConfigDO == null || memberRightConfigDO.getStatus().equals(EnableDisableStatus.DISABLE.getCode()) || memberRightConfigDO.getParameter().compareTo(new BigDecimal(0)) == 0) {
            return true;
        }

        BigDecimal plusPoint = BigDecimal.ZERO;
        switch (memberRightTypeEnum) {
            //折扣
            case PRICE_RIGHT:
                break;
            //返现
            case RETURN_MONEY_RIGHT:
                //返现金额保留两位小数
                plusPoint =  new BigDecimal(memberRightConfigDO.getParameter().doubleValue() * tradeAmount).setScale(2, RoundingMode.HALF_UP);
                levelRightDO.setSumReturnMoney(levelRightDO.getSumReturnMoney().add(plusPoint));
                break;
            //积分
            case SCORE_POINTS_RIGHT:
                plusPoint =  new BigDecimal(Math.round(memberRightConfigDO.getParameter().doubleValue() * tradeAmount));
                levelRightDO.setSumPoint(levelRightDO.getSumPoint() + plusPoint.intValue());
                levelRightDO.setCurrentPoint(levelRightDO.getCurrentPoint() + plusPoint.intValue());
                break;
            default:
                break;
        }

        //Step 2: 权益获取记录
        MemberRightHistoryDO rightHistoryDO = new MemberRightHistoryDO();
        rightHistoryDO.setCreateTime(LocalDateTime.now());
        rightHistoryDO.setMemberId(relationDO.getMemberId());
        rightHistoryDO.setRoleId(relationDO.getRoleId());
        rightHistoryDO.setSubMemberId(relationDO.getSubMemberId());
        rightHistoryDO.setSubRoleId(relationDO.getSubRoleId());
        rightHistoryDO.setRelType(relationDO.getRelType());
        rightHistoryDO.setRightTypeEnum(memberRightTypeEnum.getCode());
        rightHistoryDO.setRightTypeName(memberRightTypeEnum.getMessage());
        rightHistoryDO.setPoint(plusPoint);
        rightHistoryDO.setRemark(StringUtils.hasLength(orderNo) ? orderNo : "");
        memberRightHistoryRepository.saveAndFlush(rightHistoryDO);

        //缓存
        if(relationDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())) {
            lrcCacheService.cacheMemberRight(relationDO.getSubMemberId(), relationDO.getSubRoleId(), levelRightDO.getSumReturnMoney().doubleValue(), levelRightDO.getSumPoint(), levelRightDO.getCurrentPoint(), levelRightDO.getSumUsedPoint());
        }

        return true;
    }

    /**
     * 同时计算返现金额、权益积分
     * @param relationDO 会员关系
     * @param tradeAmount 交易金额
     * @param orderNo 订单号
     * @return 是否成功
     */
    private Boolean calculateSubMemberTradeRight(MemberRelationDO relationDO, Double tradeAmount, String orderNo) {
        //查询权益，如果没有，返回
        //下级会员的当前等级信息
        MemberLevelRightDO levelRightDO = relationDO.getLevelRight();
        if (levelRightDO == null) {
            logger.error("计算交易相关权益错误, 会员RelationId:" + relationDO.getId() + "没有当前等级数据");
            return false;
        }

        MemberLevelConfigDO memberLevelConfigDO = levelRightDO.getLevelConfig();
        if(memberLevelConfigDO == null || CollectionUtils.isEmpty(memberLevelConfigDO.getRights())) {
            return true;
        }

        //返现金额
        List<MemberRightHistoryDO> memberRightHistoryDOList = new ArrayList<>();
        BigDecimal plusReturnMoney = BigDecimal.ZERO;
        MemberRightConfigDO memberRightConfigDO = memberLevelConfigDO.getRights().stream().filter(right -> right.getRightType().equals(MemberRightTypeEnum.RETURN_MONEY_RIGHT.getCode())).findFirst().orElse(null);
        if(memberRightConfigDO != null && memberRightConfigDO.getStatus().equals(EnableDisableStatus.ENABLE.getCode()) && memberRightConfigDO.getParameter().compareTo(new BigDecimal(0)) > 0) {
            //返现金额保留两位小数
            //plusReturnMoney =  new BigDecimal(Math.round(memberRightConfigDO.getParameter().doubleValue() * tradeAmount));
            plusReturnMoney =  new BigDecimal(memberRightConfigDO.getParameter().doubleValue() * tradeAmount).setScale(2, RoundingMode.HALF_UP);
            levelRightDO.setSumReturnMoney(levelRightDO.getSumReturnMoney().add(plusReturnMoney));

            MemberRightHistoryDO rightHistoryDO = new MemberRightHistoryDO();
            rightHistoryDO.setCreateTime(LocalDateTime.now());
            rightHistoryDO.setMemberId(relationDO.getMemberId());
            rightHistoryDO.setRoleId(relationDO.getRoleId());
            rightHistoryDO.setSubMemberId(relationDO.getSubMemberId());
            rightHistoryDO.setSubRoleId(relationDO.getSubRoleId());
            rightHistoryDO.setRelType(relationDO.getRelType());
            rightHistoryDO.setRightTypeEnum(MemberRightTypeEnum.RETURN_MONEY_RIGHT.getCode());
            rightHistoryDO.setRightTypeName(MemberRightTypeEnum.RETURN_MONEY_RIGHT.getMessage());
            rightHistoryDO.setPoint(plusReturnMoney);
            rightHistoryDO.setRemark(StringUtils.hasLength(orderNo) ? orderNo.trim() : "");
            memberRightHistoryDOList.add(rightHistoryDO);
        }

        //权益积分
        memberRightConfigDO = memberLevelConfigDO.getRights().stream().filter(right -> right.getRightType().equals(MemberRightTypeEnum.SCORE_POINTS_RIGHT.getCode())).findFirst().orElse(null);
        if(memberRightConfigDO != null && memberRightConfigDO.getStatus().equals(EnableDisableStatus.ENABLE.getCode()) && memberRightConfigDO.getParameter().compareTo(new BigDecimal(0)) > 0) {
            BigDecimal plusPoint =  new BigDecimal(Math.round(memberRightConfigDO.getParameter().doubleValue() * tradeAmount));
            levelRightDO.setSumPoint(levelRightDO.getSumPoint() + plusPoint.intValue());
            levelRightDO.setCurrentPoint(levelRightDO.getCurrentPoint() + plusPoint.intValue());

            MemberRightHistoryDO rightHistoryDO = new MemberRightHistoryDO();
            rightHistoryDO.setCreateTime(LocalDateTime.now());
            rightHistoryDO.setMemberId(relationDO.getMemberId());
            rightHistoryDO.setRoleId(relationDO.getRoleId());
            rightHistoryDO.setSubMemberId(relationDO.getSubMemberId());
            rightHistoryDO.setSubRoleId(relationDO.getSubRoleId());
            rightHistoryDO.setRelType(relationDO.getRelType());
            rightHistoryDO.setRightTypeEnum(MemberRightTypeEnum.SCORE_POINTS_RIGHT.getCode());
            rightHistoryDO.setRightTypeName(MemberRightTypeEnum.SCORE_POINTS_RIGHT.getMessage());
            rightHistoryDO.setPoint(plusPoint);
            rightHistoryDO.setRemark(StringUtils.hasLength(orderNo) ? orderNo.trim() : "");
            memberRightHistoryDOList.add(rightHistoryDO);
        }

        memberLevelRightRepository.saveAndFlush(levelRightDO);
        memberRightHistoryRepository.saveAll(memberRightHistoryDOList);

        //缓存
        if(relationDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())) {
            lrcCacheService.cacheMemberRight(relationDO.getSubMemberId(), relationDO.getSubRoleId(), levelRightDO.getSumReturnMoney().doubleValue(), levelRightDO.getSumPoint(), levelRightDO.getCurrentPoint(), levelRightDO.getSumUsedPoint());
        }

        //通知支付服务，修改资金账户的返现金额
        if(plusReturnMoney.compareTo(BigDecimal.ZERO) > 0) {
            Integer returnType = relationDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode()) ? 1 : 2;
            payFeignService.notifyAssetAccountReturnMoney(relationDO.getMemberId(), relationDO.getRoleId(), relationDO.getSubMemberId(), relationDO.getSubRoleId(),returnType, plusReturnMoney.doubleValue(),orderNo);
        }

        return true;
    }

    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> returnMemberRightPoints(Long memberId, Long roleId, Integer spentType, String orderNo,String remark){
        try {
            //校验是否重复返还
            String businessNo = MemberRightReturnTypeEnum.RETURN_POINTS.getCode() + "_" + orderNo;
            MemberRightHistoryDO oldHistoryDO = memberRightHistoryRepository.findFirstByBusinessNoAndRightTypeEnum(businessNo, MemberRightTypeEnum.SCORE_POINTS_RIGHT.getCode());
            if(oldHistoryDO!=null){
                logger.warn("拦截重复返还积分 {}",orderNo);
                return Wrapper.success();
            }

            //查询积分抵扣订单金额的历史记录
            MemberRightSpendHistoryDO spendHistoryDO = memberRightSpendHistoryRepository.findFirstByBusinessNoAndSpendTypeEnum(orderNo, spentType);
            if(spendHistoryDO == null||!spendHistoryDO.getSubMemberId().equals(memberId)||!spendHistoryDO.getSubRoleId().equals(roleId)) {
                return  Wrapper.fail(ResponseCode.MC_MS_SCORE_DEDUCTION_ORDER_NOT_EXISTS);
            }

            //更新会员积分
            MemberRelationDO memberRelationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(spendHistoryDO.getMemberId(), spendHistoryDO.getRoleId(), spendHistoryDO.getSubMemberId(), spendHistoryDO.getSubRoleId());
            MemberLevelRightDO levelRightDO = memberRelationDO.getLevelRight();
            levelRightDO.setSumUsedPoint(levelRightDO.getSumUsedPoint() - spendHistoryDO.getPoint());
            levelRightDO.setCurrentPoint(levelRightDO.getSumPoint() - levelRightDO.getSumUsedPoint());
            memberLevelRightRepository.saveAndFlush(levelRightDO);

            //记录返还的积分
            MemberRightHistoryDO historyDO = new MemberRightHistoryDO();
            historyDO.setCreateTime(LocalDateTime.now());
            historyDO.setRelType(spendHistoryDO.getRelType());
            historyDO.setMemberId(spendHistoryDO.getMemberId());
            historyDO.setRoleId(spendHistoryDO.getRoleId());
            historyDO.setSubMemberId(spendHistoryDO.getSubMemberId());
            historyDO.setSubRoleId(spendHistoryDO.getSubRoleId());
            historyDO.setRelType(spendHistoryDO.getRelType());
            historyDO.setRightTypeEnum(MemberRightTypeEnum.SCORE_POINTS_RIGHT.getCode());
            historyDO.setRightTypeName(MemberRightTypeEnum.SCORE_POINTS_RIGHT.getMessage());
            historyDO.setPoint(BigDecimal.valueOf(spendHistoryDO.getPoint()));
            historyDO.setRemark(remark);
            historyDO.setBusinessNo(businessNo);
            memberRightHistoryRepository.saveAndFlush(historyDO);

            //缓存
            if(spendHistoryDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())) {
                lrcCacheService.cacheMemberRight(spendHistoryDO.getSubMemberId(), spendHistoryDO.getSubRoleId(), levelRightDO.getSumReturnMoney().doubleValue(), levelRightDO.getSumPoint(), levelRightDO.getCurrentPoint(), levelRightDO.getSumUsedPoint());
            }
            return Wrapper.success();
        } catch (Exception e) {
            logger.error("返还抵扣订单金额的积分错误", e);
            throw new BusinessException(ResponseCode.BUSINESS_ERROR);
        }
    }
}
